/**
 * Created by Ysssssss on 2021/4/12.
 */

import React, { PureComponent } from 'react'
import {withRouter} from "react-router-dom";
import { Button, Select } from "antd";
import SearchInput from "@common/presentational/SearchInput";
import CustomizeTableProvide, {CustomizeTable, CustomizeTablePagination} from "@common/presentational/CustomizeTable";
import {connect} from "react-redux";
import {
    getProductList,
    getProductTypeSelection,
    bulkDeleteProduct
} from "@sagas/productCenter";
import {getHistoryMatchParams, getQuery, handleQueryEqual, setQuery} from "@utils/setUrlQuery";
import DoubleCheck from "@common/presentational/DoubleCheck";
import ChangeProductTypeModal from "@components/productCenter/modal/ChangeProductTypeModal";
import {priceFenToYuan, priceRangePreview} from "@utils/priceConversion";


@connect(({ productCenter }) => ({
    productListPagination: productCenter.productListPagination,
    productTypeSelection: productCenter.productTypeSelection,
}), {
    getProductList,
    getProductTypeSelection,
    bulkDeleteProduct
})
@withRouter
class ProductListPage extends PureComponent {
    constructor(props) {
        super(props);
        const { showType = 'list', productType, query = '' } = getQuery(props.history)
        this.state = {
            showType,
            productType: productType ? parseInt(productType) : '',
            query: decodeURIComponent(query),
            selectedRows: []
        }
        this.tableRef = React.createRef();
        this.changeProductTypeModalRef = React.createRef()
        this.getTableInfo = this.getTableInfo.bind(this)
        this.handleSelectRowsChange = this.handleSelectRowsChange.bind(this)
        this.productTypeChange = this.productTypeChange.bind(this)
        this.paginationInfo = {}
        this.columns = [{
            key: 'name',
            dataIndex: 'name',
            title: '商品名称',
        }, {
            key: 'prod_type_name',
            dataIndex: 'prod_type_name',
            title: '分类',
        }, {
            key: 'price_range',
            dataIndex: 'price_range',
            title: '价格',
            render: text => priceRangePreview(text)
        }, {
            key: 'status',
            dataIndex: 'status',
            title: '状态',
            render: text => text === 2 ? '异常' : '正常'
        }, {
            key: 'operation',
            dataIndex: 'operation',
            title: '操作',
            render: (text, record) => (
                <div className="flex-vertical-center">
                    <div className="mgr-8 ft-hover" onClick={this.goEditPage.bind(this, record.id)}>编辑</div>
                    <DoubleCheck onClick={this.deleteProduct.bind(this, record.id)}>
                        <div className="mgr-8 ft-hover">删除</div>
                    </DoubleCheck>
                    {/*<DropdownMenu*/}
                    {/*    dropdownList={[{*/}
                    {/*        key: 'typeChange',*/}
                    {/*        name: '修改分类',*/}
                    {/*    }, {*/}
                    {/*        key: 'priceChange',*/}
                    {/*        name: '修改价格',*/}
                    {/*    }]}*/}
                    {/*    onClick={this.handleRowOperation.bind(this, record)}*/}
                    {/*>*/}
                    {/*    <div className="ft-hover">更多</div>*/}
                    {/*</DropdownMenu>*/}
                </div>
            )
        }]
    }

    componentDidMount () {
        const { productNature } = getHistoryMatchParams(this.props)
        this.props.getProductTypeSelection({ productNature })
    }

    handleValueChange (key, value) {
        if (key === 'showType') {
            this.setState({
                [key]: value
            }, this.setUrlQuery)
            return
        }
        this.setState({
            [key]: value
        }, this.initTable)
    }

    handleRowOperation (record, type) {
        switch (type) {
            case 'typeChange':
                console.log('typeChange', record)
                this.productTypeChange()
                break;
            case 'priceChange':
                console.log('priceChange', record)
                break;
            default:
                break;
        }
    }

    handleSelectRowsChange (rows) {
        this.setState({
            selectedRows: rows
        })
    }

    initTable () {
        this.tableRef.current?.initPage()
    }

    getTableInfo ({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { productNature } = getHistoryMatchParams(this.props)
        const { query, productType } = this.state
        this.props.getProductList({
            productNature,
            query,
            productType,
            pageNo: current,
            pageSize,
        })
        this.setUrlQuery()
    }

    setUrlQuery () {
        const { current, pageSize } = this.paginationInfo
        const { history } = this.props
        const { query, showType, productType } = this.state
        let params = {
            query,
            productType,
            pageNo: current,
            pageSize,
            showType
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    productTypeChange () {
        this.changeProductTypeModalRef?.current?.show()
    }

    goCreatePage () {
        const { history } = this.props
        const { productNature } = getHistoryMatchParams(this.props)
        history.push(`/product-center/product/${productNature}/detail/create`)
    }

    goEditPage (productId) {
        const { history } = this.props
        const { productNature } = getHistoryMatchParams(this.props)
        history.push(`/product-center/product/${productNature}/${productId}/detail`)
    }

    goUploadPage () {
        const { history } = this.props
        const { productNature } = getHistoryMatchParams(this.props)
        history.push(`/product-center/product/${productNature}/import`)
    }

    deleteProduct (id) {
        this.props.bulkDeleteProduct({id}, () => {
            this.getTableInfo()
        })
    }

    bulkDeleteProduct () {
        const { selectedRows } = this.state
        this.props.bulkDeleteProduct({ids: selectedRows.map(row => row.id)}, () => {
            this.getTableInfo()
        })

    }

    render () {
        const { productListPagination, productTypeSelection } = this.props
        const { query, productType, showType, selectedRows } = this.state
        return (
            <div className="table-scroll-container">
                <div className="table-params page-params flex-row-between">
                    { selectedRows.length ? (
                        <div className="flex-vertical-center">
                            {/*<Button type="primary" className="button-small mgr-16" ghost>修改分类</Button>*/}
                            {/*<Button type="primary" className="button-small mgr-16" ghost>修改价格</Button>*/}
                            <DoubleCheck triggerInBody onClick={this.bulkDeleteProduct.bind(this)}>
                                <Button className="button-small">删除</Button>
                            </DoubleCheck>
                        </div>
                    ) : (
                        <div className="flex-vertical-center">
                            <Button type="primary" className="button-small mgr-16" onClick={this.goUploadPage.bind(this)}>导入</Button>
                            <Button type="primary" className="button-small" ghost onClick={this.goCreatePage.bind(this)}>新建</Button>
                        </div>
                    ) }
                    <div className="flex-vertical-center">
                        {/*<div className="product-show-type-box bd-hover mgr-16">*/}
                        {/*    <div className={`product-show-type ft-hover${showType === 'list' ? ' selected' : ''}`}*/}
                        {/*         onClick={this.handleValueChange.bind(this, 'showType', 'list')}*/}
                        {/*    >*/}
                        {/*        <MenuOutlined />*/}
                        {/*    </div>*/}
                        {/*    <div className={`product-show-type ft-hover${showType === 'pic' ? ' selected' : ''}`}*/}
                        {/*         onClick={this.handleValueChange.bind(this, 'showType', 'pic')}*/}
                        {/*    >*/}
                        {/*        <AppstoreOutlined />*/}
                        {/*    </div>*/}
                        {/*</div>*/}
                        <Select className="mgr-16"
                                style={{width: '140px'}}
                                onChange={this.handleValueChange.bind(this, 'productType')}
                                value={productType}
                        >
                            <Select.Option key="all" value="">全部</Select.Option>
                            { productTypeSelection.map(productTypeGroup => (
                                <Select.OptGroup key={productTypeGroup.id} label={productTypeGroup.name}>
                                    { productTypeGroup.subs.map(productType => (
                                        <Select.Option
                                            key={productType.id}
                                            value={productType.id}
                                        >
                                            { productType.name }
                                        </Select.Option>
                                    )) }
                                </Select.OptGroup>
                            ))}
                        </Select>
                        <SearchInput style={{width: 240}}
                                     onChange={this.handleValueChange.bind(this, 'query')}
                                     initValue={query}
                                     value={query}
                                     placeholder="商品名称"
                        />
                    </div>
                </div>
                <CustomizeTableProvide ref={this.tableRef} tableKey="productList" onChange={this.getTableInfo}>
                    <div className="table-list">
                        <CustomizeTable
                            columns={this.columns}
                            dataSource={productListPagination.prods || []}
                            pagination
                            selectionInfo={{
                                keyValue: 'id',
                                onChange: this.handleSelectRowsChange,
                            }}
                        />
                    </div>
                    <div className="table-pagination">
                        <CustomizeTablePagination
                            total={productListPagination.total}
                        />
                    </div>
                </CustomizeTableProvide>
                <ChangeProductTypeModal ref={this.changeProductTypeModal} selectionList={productTypeSelection}/>
            </div>
        )
    }
}

export default ProductListPage